<template>
    <div class="wrapper">
      <!-- header部分 -->
      <button class="back-arrow" @click="goBack"></button>
      <header class="header">
        <p>商家注册</p>
      </header>
      <!-- 表单部分 -->
      <ul class="form-box">
        <li class="form-item">
          <div class="title">
            手机号码：
          </div>
          <div class="content">
            <input type="text" @blur="checkUserId" v-model="businesser.businesserId" placeholder="手机号码">
          </div>
        </li>
        <li class="form-item">
          <div class="title">
            密码：
          </div>
          <div class="content">
            <input type="password" v-model="businesser.password" placeholder="密码" @input="checkPasswordStrength">
            <div class="password-strength" :style="{ backgroundColor: passwordStrengthColor }"></div>
          </div>
        </li>
        <li class="form-item">
          <div class="title">
            确认密码：
          </div>
          <div class="content">
            <input type="password" v-model="confirmPassword" placeholder="确认密码">
          </div>
        </li>
        <li class="form-item">
          <div class="title">
            商家名称：
          </div>
          <div class="content">
            <input type="text" v-model="businesser.businesserName" placeholder="商家名称">
          </div>
        </li>
        <li class="form-item">
          <div class="title">
            上传头像：
          </div>
          <div class="content">
            <input type="file" @change="handleFileChange" accept="image/png">
          </div>
        </li>
      </ul>
      <div class="button-login">
        <button @click="register">注册</button>
      </div>
       <!-- Alert Modal -->
       <alert-modal v-if="alertVisible" :visible.sync="alertVisible" :message="alertMessage"></alert-modal>
      <!-- 底部菜单部分 -->
      <Footer></Footer>
    </div>
  </template>

  
  <script>
  import Footer from '../components/Footer.vue';
  import AlertModal from '../views/AlertModal.vue';
  import JSEncrypt from 'jsencrypt';
  import request from '../request.js';
  export default {
    name: 'Bregister',
    data() {
      return {
        businesser: {
          businesserId: '',
          password: '',
          businesserName: '',
          businesserImg: '', // 添加这个属性
          orderTypeId: 1,
          businessAddress: '',
          businessExplain:'',
          starPrice: 15,
          deliveryPrice: 3


        },
        PublicKey: '' , // 公钥
        confirmPassword: '',
        passwordStrengthColor: '#ccc', // 默认颜色
        alertVisible: false,
        alertMessage: ''
      };
    },
    methods: {
      goBack() {
          console.log('Trying to go back...');
          this.$router.go(-1); // 相当于浏览器的后退操作
        },
      checkUserId() {
        const regex = /^1(3\d|4[5-9]|5[0-35-9]|6[5-7]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
        if (!regex.test(this.businesser.businesserId)) {
                    this.alertMessage ='手机号码格式不正确!';
                    this.alertVisible = true;
                    return;
              }
        this.$axios.post(`businesses/${this.businesser.businesserId}`).then(response => {
          if (response.data===1) {
            this.businesser.businesserId = '';
           this.alertMessage ='此手机号码已存在！';
           this.alertVisible = true;
          }
          else this.PublicKey = response.data;
        }).catch(error => {
          console.error(error);
        });
      },
      handleFileChange(event) {
        const file = event.target.files[0];
        if (file) {
          const reader = new FileReader();
          reader.onload = (e) => {
            this.businesser.businesserImg = e.target.result;
          };
          reader.readAsDataURL(file);
        }
      },
      checkPasswordStrength() {
        const strength = this.getPasswordStrength(this.businesser.password);
        switch (strength) {
          case 0:
            this.passwordStrengthColor = 'red';
            break;
          case 1:
            this.passwordStrengthColor = 'red';
            break;
          case 2:
            this.passwordStrengthColor = 'yellow';
            break;
          case 3:
            this.passwordStrengthColor = 'yellow';
            break;
          case 4:
            this.passwordStrengthColor = 'green';
            break;  
          case 5:
            this.passwordStrengthColor = 'green';
            break;
        }
      },
      getPasswordStrength(password) {
        let strength = 0;
        if (password.length > 5) strength++;
        if (password.match(/[a-z]/)) strength++;
        if (password.match(/[A-Z]/)) strength++;
        if (password.match(/[0-9]/)) strength++;
        if (password.match(/[\W_]/)) strength++;
        return strength;
      },
      register() {
        if (this.businesser.businesserId == '') {
         this.alertMessage ='手机号码不能为空！';
         this.alertVisible = true;
          return;
        }
        if (this.businesser.password == '') {
          this.alertMessage ='密码不能为空！';
          this.alertVisible = true;
          return;
        }
        if (this.businesser.password != this.confirmPassword) {
          this.alertMessage ='两次输入的密码不一致！';
          this.alertVisible = true;
          return;
        }
        if (this.businesser.businesserName == '') {
          this.alertMessage ='用户名不能为空！';
          this.alertVisible = true;
          return;
        }
  
        const encryptor = new JSEncrypt()
        encryptor.setPublicKey(this.PublicKey)  // 放入公钥
        let passwordAfterEncrypt = encryptor.encrypt(this.businesser.password)  // 加密密码 
  
        // 注册请求，包括图像数据
        this.$axios.post('businesses/', this.$qs.stringify({
          businessPassId: this.businesser.businesserId,
          password: passwordAfterEncrypt,
          businessName: this.businesser.businesserName,
          businessImg: this.businesser.businesserImg, // 确保图像数据被发送
          orderTypeId: 1,
          businessAddress: '北洋园',
          businessExplain: '吃的',
          starPrice: 15,
          deliveryPrice: 3,
          remarks: 0,
        })).then(response => {
          if (response.data > 0) {
            this.alertMessage ='注册成功！';
            this.alertVisible = true;
            this.$router.go(-1);
          } else {
           this.alertMessage ='注册失败！';
           this.alertVisible = true;
          }
        }).catch(error => {
          console.error(error);
        });
      }
    },
    components: {
      Footer,AlertModal
    }
  }
  </script>
  
  <style scoped>
    /****************** 总容器 ******************/
    .wrapper {
      width: 100%;
      min-height: 100vh;
      background-color: white;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 6rem; /* 增加内边距以避免内容被固定头部覆盖 */
      box-sizing: border-box;
      position: relative;
    }
  /****************** 返回键 ******************/
 .back-arrow {
  position: fixed; /* 固定定位 */
  left: 2.5vw; /* 距离屏幕左端像素 */
  top: 2.5vw; /* 距离屏幕顶部像素 */
  width: 8vw; /* 使用视口宽度的百分比 */
  height: 8vw; /* 使用视口宽度的百分比，保持宽高比 */
  background-color: transparent; /* 设置背景为透明 */
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border: none; /* 隐藏边框 */
  transition: color 0.3s ease; /* 字体颜色变化动画 */
}

.back-arrow::before {
  content: '\f053'; /* 使用 FontAwesome 的左箭头图标 */
  font-family: 'FontAwesome'; /* FontAwesome 字体 */
  font-size: 5vh; /* 使用视口高度的百分比，确保在不同设备上也合适 */
  color: #14c4f4; /* 字体颜色 */
  transition: color 0.3s ease; /* 字体颜色变化动画 */
}

.back-arrow:hover::before {
  color: #dc0aaf; /* 鼠标悬停时的颜色变化 */
}
    /****************** 表单部分 ******************/
    .form-box {
      width: calc(100% - 4rem);
      max-width: 480px;
      background: rgba(255, 255, 255, 0.95);
      border-radius: 8px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1), 0 1px 3px rgba(0, 0, 0, 0.08);
      padding: 2rem;
      box-sizing: border-box;
    }
  
    .form-item {
      display: flex;
      align-items: center;
      margin-bottom: 1rem;
    }
  
    .title {
      flex: 1;
      font-size: 1.2rem;
      color: #333;
    }
  
    .content {
      flex: 2;
    }
  
    .content input {
      width: 100%;
      padding: 0.5rem;
      border: 1px solid #ddd;
      border-radius: 4px;
      font-size: 1rem;
      transition: border-color 0.3s, box-shadow 0.3s;
    }
  
    .content input:focus {
      border-color: #2575fc;
      box-shadow: 0 0 0 3px rgba(37, 117, 252, 0.5);
      outline: none;
    }
  
    .password-strength {
      height: 4px;
      width: 100%;
      border-radius: 4px;
      margin-top: 0.5rem;
    }
  
    .button-login {
      margin-top: 1.5rem;
    }
  
    .button-login button {
      width: 100%;
      padding: 0.75rem;
      font-size: 1.1rem;
      color: white;
      background-color: #38CA73;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s, transform 0.2s;
    }
  
    .button-login button:hover {
      background-color: #2f995b;
    }
  
    .button-login button:active {
      transform: scale(0.98);
    }
  
    /** 底部菜单部分 **/
    Footer {
      margin-top: auto;
    }
  </style>